package com.pkdl.forms;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;

import com.pkdl.dao.DichVuDAO;
import com.pkdl.dto.DichVuDTO;
import com.pkdl.tables.TableDichVu;

@SuppressWarnings("serial")
public class DlgQuanLyDichVu extends JDialog {
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			DlgQuanLyDichVu dialog = new DlgQuanLyDichVu(null, true);
			dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			dialog.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private DichVuDAO dvDAO;
	private JTable tblData;
	private JTextField txtMaDV;
	private JTextField txtTenDV;
	private JTextArea txtMoTa;
	private JTextField txtPhiDV;
	private JLabel lblDVFormated;

	/**
	 * Create the dialog.
	 */
	public DlgQuanLyDichVu(Frame parent, boolean modal) {
		super(parent, modal);
		this.setTitle("Quan ly dich vu");
		this.setBounds(100, 100, 952, 565);
		this.setLocationRelativeTo(null);
		this.getContentPane().setLayout(new BorderLayout());
		{
			JPanel panel = new JPanel();
			this.getContentPane().add(panel, BorderLayout.CENTER);
			panel.setLayout(new BorderLayout(0, 0));
			{
				JPanel panel_1 = new JPanel();
				panel_1.setPreferredSize(new Dimension(452, 10));
				panel.add(panel_1, BorderLayout.WEST);
				panel_1.setLayout(new BorderLayout(0, 0));
				{
					JPanel panel_2 = new JPanel();
					panel_2.setBackground(SystemColor.textHighlight);
					panel_1.add(panel_2, BorderLayout.NORTH);
					panel_2.setLayout(new BorderLayout(0, 0));
					{
						JLabel lblNewLabel = new JLabel(
								"  Danh s\u00E1ch d\u1ECBch v\u1EE5");
						lblNewLabel.setHorizontalAlignment(SwingConstants.LEFT);
						lblNewLabel.setForeground(Color.WHITE);
						lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 18));
						lblNewLabel.setPreferredSize(new Dimension(46, 32));
						panel_2.add(lblNewLabel, BorderLayout.CENTER);
					}
				}
				{
					JScrollPane scrollPane = new JScrollPane();
					panel_1.add(scrollPane, BorderLayout.CENTER);
					{
						this.tblData = new JTable();
						this.tblData.addMouseListener(new MouseAdapter() {
							@Override
							public void mousePressed(MouseEvent evt) {
								DlgQuanLyDichVu.this.actionSelect(evt);
							}
						});
						this.tblData.setFillsViewportHeight(true);
						this.tblData.setModel(new DefaultTableModel(
								new Object[][] { { null, null, null },
										{ null, null, null },
										{ null, null, null }, }, new String[] {
										"New column", "New column",
										"New column" }));
						scrollPane.setViewportView(this.tblData);
					}
				}
			}
			{
				JPanel panel_1 = new JPanel();
				panel.add(panel_1, BorderLayout.CENTER);
				panel_1.setLayout(null);

				JLabel lblNewLabel_1 = new JLabel(
						"Th\u00F4ng tin d\u1ECBch v\u1EE5");
				lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 18));
				lblNewLabel_1.setForeground(new Color(0, 128, 0));
				lblNewLabel_1.setBounds(10, 0, 287, 31);
				panel_1.add(lblNewLabel_1);

				JLabel lblNewLabel_2 = new JLabel("M\u00E3 DV");
				lblNewLabel_2.setBounds(34, 57, 46, 14);
				panel_1.add(lblNewLabel_2);

				this.txtMaDV = new JTextField();
				this.txtMaDV.setEditable(false);
				this.txtMaDV.setBounds(118, 54, 86, 20);
				panel_1.add(this.txtMaDV);
				this.txtMaDV.setColumns(10);
				{
					JLabel lblTnDv = new JLabel("T\u00EAn DV");
					lblTnDv.setBounds(34, 85, 46, 14);
					panel_1.add(lblTnDv);
				}
				{
					this.txtTenDV = new JTextField();
					this.txtTenDV.setColumns(10);
					this.txtTenDV.setBounds(118, 82, 276, 20);
					panel_1.add(this.txtTenDV);
				}
				{
					JLabel lblPhDv = new JLabel("Ph\u00ED DV");
					lblPhDv.setBounds(34, 113, 46, 14);
					panel_1.add(lblPhDv);
				}
				{
					this.txtPhiDV = new JTextField();
					this.txtPhiDV.addKeyListener(new KeyAdapter() {
						@Override
						public void keyReleased(KeyEvent ke) {
							char c = ke.getKeyChar();
							if ((!(Character.isDigit(c))) && (c != '\b')) {
								ke.consume();
							} else {
								DlgQuanLyDichVu.this.formatGia();
							}
						}
					});
					this.txtPhiDV.setColumns(10);
					this.txtPhiDV.setBounds(118, 110, 86, 20);
					panel_1.add(this.txtPhiDV);
				}
				{
					JLabel lblMT = new JLabel("M\u00F4 t\u1EA3");
					lblMT.setBounds(34, 141, 46, 14);
					panel_1.add(lblMT);
				}

				this.txtMoTa = new JTextArea();
				this.txtMoTa.setBorder(new LineBorder(new Color(0, 0, 0)));
				this.txtMoTa.setLineWrap(true);
				this.txtMoTa.setBounds(118, 141, 345, 129);
				panel_1.add(this.txtMoTa);

				JButton btnLuu = new JButton("L\u01B0u");
				btnLuu.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						DlgQuanLyDichVu.this.actionLuu();
					}
				});
				btnLuu.setIcon(new ImageIcon(DlgQuanLyDichVu.class
						.getResource("/com/pkdl/resources/45.png")));
				btnLuu.setBounds(393, 294, 89, 23);
				panel_1.add(btnLuu);

				JButton btnXoa = new JButton("X\u00F3a");
				btnXoa.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						DlgQuanLyDichVu.this.actionDelete();
					}
				});
				btnXoa.setIcon(new ImageIcon(DlgQuanLyDichVu.class
						.getResource("/com/pkdl/resources/001_29.png")));
				btnXoa.setBounds(294, 294, 89, 23);
				panel_1.add(btnXoa);

				JButton btnThemMoi = new JButton("Th\u00EAm m\u1EDBi");
				btnThemMoi.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						DlgQuanLyDichVu.this.resetFields();
					}
				});
				btnThemMoi.setIcon(new ImageIcon(DlgQuanLyDichVu.class
						.getResource("/com/pkdl/resources/Eraser-icon.png")));
				btnThemMoi.setBounds(172, 294, 112, 23);
				panel_1.add(btnThemMoi);

				this.lblDVFormated = new JLabel("");
				this.lblDVFormated.setBounds(209, 113, 112, 14);
				panel_1.add(this.lblDVFormated);
			}
		}
		this.loadData();
	}

	/**
	 * Delete item
	 */
	private void actionDelete() {
		if (this.txtMaDV.getText().trim().equals("")) {
			JOptionPane.showMessageDialog(null, "Vui long chon dong de xoa",
					"Announcement", JOptionPane.ERROR_MESSAGE);
			return;
		}
		this.dvDAO = new DichVuDAO();
		if (this.dvDAO.delete(Integer.parseInt(this.txtMaDV.getText()))) {
			this.loadData();
			this.resetFields();
			JOptionPane.showMessageDialog(null, "Xoa du lieu thanh cong",
					"Announcement", JOptionPane.INFORMATION_MESSAGE);
		} else {
			JOptionPane.showMessageDialog(null, "Khong the xoa du lieu",
					"Announcement", JOptionPane.ERROR_MESSAGE);
		}
	}

	/**
	 * Them moi, xoa, cap nhat danh sach thuoc
	 */
	private void actionLuu() {
		AtomicReference<Object> errText = new AtomicReference<Object>("");
		if (!this.validateInputData(errText)) {
			JOptionPane.showMessageDialog(null, errText.get(), "Announcement",
					JOptionPane.ERROR_MESSAGE);
			return;
		}

		this.dvDAO = new DichVuDAO();

		// Them moi
		if (this.txtMaDV.getText().trim().equals("")) {
			DichVuDTO dv = new DichVuDTO(this.txtTenDV.getText(),
					Long.parseLong(this.txtPhiDV.getText()),
					this.txtMoTa.getText());
			if (this.dvDAO.insert(dv)) {
				this.loadData();
				this.resetFields();
				JOptionPane.showMessageDialog(null, "Them du lieu thanh cong",
						"Announcement", JOptionPane.INFORMATION_MESSAGE);
			} else {
				JOptionPane.showMessageDialog(null, "Khong the them du lieu",
						"Announcement", JOptionPane.ERROR_MESSAGE);
			}
		} else {
			// Cap nhat
			DichVuDTO dv = this.dvDAO.selectById(Integer.parseInt(this.txtMaDV
					.getText()));
			dv.setTenDichVu(this.txtTenDV.getText());
			dv.setPhiDichVu(Long.parseLong(this.txtPhiDV.getText()));
			dv.setMoTa(this.txtMoTa.getText());
			if (this.dvDAO.update(dv)) {
				this.loadData();
				JOptionPane.showMessageDialog(null,
						"Cap nhat du lieu thanh cong", "Announcement",
						JOptionPane.INFORMATION_MESSAGE);
			} else {
				JOptionPane.showMessageDialog(null,
						"Khong the cap nhat du lieu", "Announcement",
						JOptionPane.ERROR_MESSAGE);
			}
		}
	}

	/**
	 * Lua chon item trong danh sach
	 */
	private void actionSelect(MouseEvent evt) {
		int modifiers = evt.getModifiers();
		if ((modifiers & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
			if (this.tblData.getSelectedRow() == -1) {
				return;
			}

			if (this.tblData.getValueAt(this.tblData.getSelectedRow(), 0) == null) {
				return;
			}

			if (evt.getClickCount() == 1) {
				String madv = ((JLabel) this.tblData.getValueAt(
						this.tblData.getSelectedRow(), 0)).getName().trim();
				this.dvDAO = new DichVuDAO();
				DichVuDTO dv = this.dvDAO.selectById(Integer.valueOf(madv));
				this.txtMaDV.setText(String.valueOf(dv.getMaDichVu()));
				this.txtTenDV.setText(dv.getTenDichVu());
				this.txtPhiDV.setText(String.valueOf(dv.getPhiDichVu()));
				this.txtMoTa.setText(dv.getMoTa());
				this.formatGia();
			}
		}
	}

	/**
	 * Format gia
	 */
	private void formatGia() {
		if (!this.txtPhiDV.getText().trim().equals("")) {
			NumberFormat numberFormatter = new DecimalFormat("#,###,###");
			String formattedNumber = numberFormatter.format(Long
					.parseLong(this.txtPhiDV.getText()));
			this.lblDVFormated.setText(formattedNumber);
		} else {
			this.lblDVFormated.setText("");
		}
	}

	/**
	 * Load danh sach thuoc
	 */
	private void loadData() {
		this.dvDAO = new DichVuDAO();
		List<DichVuDTO> ds = this.dvDAO.selectAll();
		TableDichVu table = new TableDichVu(ds);
		table.loadDataIntoTable(this.tblData);
	}

	/**
	 * Reset fields
	 */
	private void resetFields() {
		this.txtMaDV.setText("");
		this.txtTenDV.setText("");
		this.txtPhiDV.setText("");
		this.txtMoTa.setText("");
		this.lblDVFormated.setText("");
	}

	/**
	 * Validate user input
	 * 
	 * @return true: valid / false: invalid
	 */
	private boolean validateInputData(AtomicReference<Object> errText) {
		if (this.txtTenDV.getText().trim().equals("")) {
			errText.set("Ban chua nhap ten dich vu");
			return false;
		}
		if (this.txtPhiDV.getText().trim().equals("")) {
			errText.set("Ban chua nhap phi dich vu");
			return false;
		}
		return true;
	}
}
